<template>
    <el-container>
        <el-main>
            <el-form :inline="true">
                <!-- 搜索框 -->
                <el-form-item class="search-item">
                    <el-date-picker v-model="searchForm.startDate" type="date" placeholder="选择起始日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-date-picker v-model="searchForm.endDate" type="date" placeholder="选择结束日期">
                    </el-date-picker>
                </el-form-item>

                <!-- 操作按钮 -->
                <el-form-item class="search-item">
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="handleResetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 图表 -->
            <el-container id="chart" />
        </el-main>
    </el-container>
</template>


<script>
import getStatistics from '@/api/statistics';
import { renderChart } from "@/common/utils";
import { STATISTICS_DATA } from '@/common/constants';

export default {
    data() {
        return {
            /**
             * 搜索栏数据
             * @type {Object}
             */
            searchForm: {
                startDate: "",
                endDate: "",
            },

            /**
             * 图表数据
             * @type {Object}
             */
            chartData: STATISTICS_DATA,
        };
    },
    mounted() {
        /**
         * 渲染图表
         */
        this.handleRenderChart();
    },
    methods: {
        /**
         * 重置查询
         * @returns {void}
         */
        handleResetSearch() {
            this.searchForm = {
                startDate: "",
                endDate: "",
            };
        },

        /**
        * 根据统计数据渲染图表
        * @return {void}
        */
        handleRenderChart() {
            renderChart('chart', this.chartData);
        },

        /**
         * 根据日期范围筛选统计数据
         * @returns {Array}
         */
        async handleSearch() {
            try {
                this.$loading({ lock: true, text: "正在查询，请稍后..." });

                // 调用查询统计数据接口
                const response = await getStatistics(this.searchForm);

                if (response.success) {
                    // 更新图标数据
                    this.chartData = response.data;

                    // 更新图表
                    this.handleRenderChart();
                    this.handleResetSearch();
                    this.$message.success('查询数据成功');
                } else {
                    this.$message.error('查询数据失败');
                }
            } catch (error) {
                this.$message.error(error.message || '查询数据失败');
            } finally {
                this.$loading().close();
            }
        },

    },
};
</script>

<style scoped lang="scss">
@import url('@/assets/scss/statistics.scss');
</style>
